<?php

declare(strict_types=1);

namespace app\api\controller;

use app\common\model\User;
use app\common\tool\Result;
use think\exception\ValidateException;
use app\common\model\ExamineTake;
use app\common\model\ExamineUser;
use app\common\model\ExamineBank;
use app\common\model\ExamineAnswer;
use app\common\model\Examine as ExamineModel;
use app\common\model\Cate;
use app\common\model\Exam;

class Examine extends Base
{

    /**
     * 学习中心列表
     */
    public function getList()
    {
        try {
            $param = $this->request->param();
            $examine_id =  ExamineUser::where(['uid'=>$this->user->id])->column('examine_id');
            $examine = ExamineModel::where([['cate','=',$this->user->cate],['end_time','>=',time()],['id','in',$examine_id]])->field('id,title,status,score,exam_date,exam_time,start_time,duration,types')->append(['typesText','timeText','statusText'])->select();
            $list['examine'] = $examine;
            $examine_list = ExamineModel::where([['cate','=',$this->user->cate],['id','in',$examine_id]])->field('id,title,score,exam_date,exam_time,end_time,duration,types')->append(['typesText','timeText'])->select();
            foreach($examine_list as $k=>$v){
                if($v->end_time>time()){
                    $v->status=4;
                    $v->my_score='';
                    $v->status_title='未公布';
                }else{
                    $ExamineTake = ExamineTake::where(['uid'=>$this->user->id,'examine_id'=>$v['id']])->find();
                    if(empty($ExamineTake)){
                        $v->status_title = '缺考';
                        $v->my_score=0;
                        $v->status=3;
                    }else{
                        $v->status=$ExamineTake->status;
                        $v->my_score=$ExamineTake->score;
                        $v->status_title=$ExamineTake->statusText;
                    }
                }
            }
            $list['title']=$this->user->cateText.'考试';
            $list['list']=$examine_list;
            return Result::success('获取成功！',$list);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     * 课程章节详情
     */
    public function info()
    {
        try {
            $param = $this->request->param();
            $item = ExamineModel::where('id', $param['id'])->field('id,title,score,exam_date,exam_time,end_time,duration,types,content')->append(['typesText','timeText'])->find();
            if (empty($item)) {
                return Result::fail('暂无详情');
            }
            $url = 'https://' . $_SERVER['SERVER_NAME'] . '/uploads/';
            $item->content = htmlspecialchars_decode(str_replace('/uploads/', $url, $item->content));
            $item->content = str_replace('\\', '', $item->content);
            return Result::success('获取成功！', $item);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     * 开始答题
     */
    public function startAnswer()
    {
        try {
            $param = $this->request->post();
            $this->validate($param, 'ExamineTake');
            return Result::fastReturn(ExamineTake::startAnswer($param,$this->user));
        }catch (\Exception $e){
            return Result::fail($e->getMessage());
        }
    }
    
    /**
     * 获取试卷内容
     */
    public function getExam()
    {
        try {
            $param = $this->request->get();
            $user = $this->user;
            $cate = Cate::where('id', $user->cate)->find();
            if (empty($cate)) {
                return ['code' => -1, 'msg' => '暂无课程类型'];
            }
            $info = ExamineTake::where(['uid' => $user->id,'examine_id'=>$param['id']])->find();
            $find = ExamineModel::where(['id'=>$param['id']])->find();
            if (empty($info)) {
                return ['code' => -1, 'msg' => '暂无考试试卷'];
            }
            $data['title'] = $find['title'];
            $data['examine_id'] = $find['id'];
            $data['end_time'] = $find->end_time;
            $data['status'] = $info->status;
            $data['count'] = $info['radio_num'] + $info['check_num'];
            $data['score'] = $info->status == 3 ? '' : $info->score;
            $data['answer_count'] = ExamineAnswer::where(['examine_id' => $param['id'],'uid' => $user->id])->count();
            $radio = ExamineBank::where(['examine_id' => $param['id'], 'uid' => $user->id, 'types' => 1])->order('id asc')->field('exam_id as id')->select();
            foreach ($radio as $k => $value) {
                $value['bh'] = $k + 1;
                if ($info->status == 1) {
                    $value['status'] = 3; //未答题
                } else {
                    $PracticeAnswer = ExamineAnswer::where(['examine_id' => $param['id'],'exam_id'=>$value['id'],'uid' => $user->id])->find();
                    if (empty($PracticeAnswer)) {
                        $value['status'] = 3; //未答题
                    } else {
                        $value['status'] = $PracticeAnswer->types == 1 ? 1 : 2; //1：正确，2：错误
                    }
                }
                $radio[$k] = $value;
            }
            $data['radio'] = [
                'title' => '单选题（' . ($info['radio_num'] * $info['radio_score']) . '分）',
                'count' => $info['radio_num'],
                'list' => $radio,
            ];
            $check = ExamineBank::where(['examine_id' => $param['id'], 'uid' => $user->id, 'types' => 2])->order('id asc')->field('exam_id as id')->select();
            foreach ($check as $k => $value) {
                $value['bh'] = $k + 1;
                if ($info->status == 1) {
                    $value['status'] = 3; //未答题
                } else {
                    $PracticeAnswer = ExamineAnswer::where(['examine_id' => $param['id'], 'exam_id'=>$value['id'],'uid' => $user->id])->find();
                    if (empty($PracticeAnswer)) {
                        $value['status'] = 3; //未答题
                    } else {
                        $value['status'] = $PracticeAnswer->types == 1 ? 1 : 2; //1：正确，2：错误
                    }
                }
                $check[$k] = $value;
            }
            $data['check'] = [
                'title' => '多选题（' . ($info['check_num'] * $info['check_score']) . '分）',
                'count' => $info['check_num'],
                'list' => $check,
            ];
            $topic_id = !empty($radio)?$radio[0]['id']:(!empty($check)?$check[0]['id']:'');
            $topic = ExamineModel::getTopic($topic_id);
            $data['topic'] = $topic;
            return Result::success('获取成功！', $data);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    
    /**
     * 获取题目
     */
    public  function getTopic($id)
    {
        try {
            $param = $this->request->get();
            $user = $this->user;
            $cate = Cate::where('id', $user->cate)->find();
            if (empty($cate)) {
                return ['code' => -1, 'msg' => '暂无课程类型'];
            }
            $info = ExamineModel::where(['id'=>$param['examine_id']])->find();
            if (empty($info)) {
                return ['code' => -1, 'msg' => '暂无考试试卷'];
            }
            $data = ExamineModel::getTopic($id); 
            if ($info->status != 3) {
                $PracticeAnswer = ExamineAnswer::where(['examine_id' => $info['examine_id'], 'exam_id'=>$id,'uid' => $user->id])->find();
                $data['my_answer'] =  !empty($PracticeAnswer)?$PracticeAnswer['answer']:'';
            }
            return Result::success('获取成功！', $data);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     * 交卷
     */
    public function submit()
    {
        try {
            $param = $this->request->post();
            return Result::fastReturn(ExamineAnswer::submit($param,$this->user));
        }catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
}
